/**
 * @description: 这是Eirudy创建的类~
 * @author: Eirudy
 * @hope: 憧憬成为java大师
 **/

package org.eirudy.shareimage.manager.upload;

import cn.hutool.core.io.FileUtil;
import org.eirudy.shareimage.exception.ErrorCode;
import org.eirudy.shareimage.exception.ThrowUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 文件上传
 */
@Service
public class FilePictureUpload extends PictureUploadTemplate {
    @Override
    protected void validPicture(Object inputSource) {
        // 判断文件是否为空
        MultipartFile multipartFile = (MultipartFile) inputSource;
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR,"上传文件为空");
        //

        // 判断文件大小
        long fileSize = multipartFile.getSize();
        long limitSize = 10 * 1024 * 1024L;
        ThrowUtils.throwIf(fileSize > limitSize,ErrorCode.PARAMS_ERROR,"传输文件不能超过2M");

        //判断文件是否是图片
        String suffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final List<String> FORMAT_TYPE = Arrays.asList("jpeg", "jpg", "png", "wep");
        ThrowUtils.throwIf(!FORMAT_TYPE.contains(suffix),ErrorCode.PARAMS_ERROR,"文件类型错误");
    }

    @Override
    protected String getOriginFilename(Object inputSource) {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        return multipartFile.getOriginalFilename();
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        MultipartFile multipartFile = (MultipartFile) inputSource;
        multipartFile.transferTo(file);
    }
}
